#coding=utf-8
import librosa
import os
import json
import numpy as np


def save_data(data):
 	f=open("level.json","w")
 	f.write(json.dumps(data)+",")
 	f.close()


def analysis(nameKey,path,configJosn):
	y, sr = librosa.load(path)
	tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)

	#获取音乐时间
	musicTimer=librosa.get_duration(filename=path)
	#将时间转化为帧数
	musicFrame=librosa.time_to_frames(musicTimer)
	#获取每个节拍平均相隔几帧   每首歌的节拍是大概固定的
	beatsDis=musicFrame/len(beat_frames)




	# 峰值点 帧数
	onset_env = librosa.onset.onset_strength(y=y, sr=sr,hop_length=512,aggregate=np.median)
	peaks = librosa.util.peak_pick(onset_env, 3, 3,3, 5, 0.5, 12)
	peaks_to_timer= librosa.frames_to_time(peaks, sr=sr)
	
	
	dataStr="[0,"
	for item in peaks_to_timer:
		dataStr=dataStr+str(item)+","
	dataStr=dataStr[:len(dataStr)-1]
	dataStr=dataStr+"]"

	
	json={}
	json["timer"]=musicTimer
	json["rhythm"]=dataStr
	configJosn[nameKey]=json


def getFileList(configJosn):
	audioList = os.listdir('music')
	for tmp in audioList:
		audioPath = os.path.join('music', tmp)
		if audioPath.endswith('.mp3'):
			name=tmp[:tmp.find('.mp3')]
			print("print "+audioPath+" audio datas----")
			analysis(name,audioPath,configJosn)
if __name__=="__main__":
	configJosn={}
	getFileList(configJosn)
	save_data(configJosn)


